package com.example.multithread;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.io.Serializable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadPoolActivity extends AppCompatActivity {
    public static final String TAG = ThreadPoolActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 使用Executors的工厂方法创建固定大小的线程池
        final ExecutorService executor = Executors.newFixedThreadPool(2);
        try {
            for (int i = 1; i <= 3; i++) {
                // 分配任务，并将其加入到线程池
                String taskName = "任务-" + i;
                executor.execute(new Task(taskName));
                Log.i(TAG, "put " + taskName);
            }
            executor.shutdown();
            executor.awaitTermination(1, TimeUnit.HOURS);
            Log.i(TAG, "线程池中启动的任务已全部完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //任务类
    public static class Task implements Runnable, Serializable {
        //保存任务所需要的数据
        private Object data;
        public Task(Object tasks) {
            this.data = tasks;
        }
        public void run() {
            // 处理一个任务，输出日志
            Log.i(TAG, Thread.currentThread().getName());
            Log.i(TAG, "start " + data);
            try {
                //便于观察，等待一段时间
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            data = null;
        }
    }
}
